#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月19日

@author: Administrator
'''
import urllib

from django.views.decorators.csrf import requires_csrf_token
from django.http.response import HttpResponseNotFound, HttpResponseServerError

FRONTEND_LOCATION_REDIRECT_TEMPLATE = '''
<!DOCTYPE html>
<html lang="zh-CN">
    <script>
        window.location = "%s";
    </script>
</html>
'''

# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
@requires_csrf_token
def page_not_found(request):
    """
    function: 自定义404 handler
    """
    
    if request.META.has_key('RAW_URI'):
        referer = 'http://%s%s' % (request.META['HTTP_HOST'], request.META['RAW_URI'])
    else:
        referer = 'http://%s%s?%s' % (request.META['HTTP_HOST'], request.META['PATH_INFO'], request.META['QUERY_STRING'])
    
    next_url = 'http://www.auoffice.com/error/404/?referer=%s' % urllib.quote(referer)
    html = FRONTEND_LOCATION_REDIRECT_TEMPLATE % next_url
    
    return HttpResponseNotFound(html)


@requires_csrf_token
def server_error(request):
    """
    function: 自定义500 handler
    """
    
    if request.META.has_key('RAW_URI'):
        referer = 'http://%s%s' % (request.META['HTTP_HOST'], request.META['RAW_URI'])
    else:
        referer = 'http://%s%s?%s' % (request.META['HTTP_HOST'], request.META['PATH_INFO'], request.META['QUERY_STRING'])
    
    next_url = 'http://www.auoffice.com/error/500/?referer=%s' % urllib.quote(referer)
    html = FRONTEND_LOCATION_REDIRECT_TEMPLATE % next_url
    
    return HttpResponseServerError(html)
